<script setup lang="tsx">
defineOptions({
  name: "paramsInfo"
});

import { queryFabDetailParams, queryFabDetailParamsSpec } from "@/api/modules/fab";
import { useCancelUpdateDomHeight, useUpdateDomHeight } from "@/hooks/useCommon";
import { useFabDetailSocket } from "@/hooks/useWebSocket";
import commonTable from "@/views/common/components/commonTable/index.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import previewSpec from "@/views/common/fab/monitoring/specOverView/components/previewSpec.vue";
import { PxButton } from "px-ui";
import { inject, onMounted, onUnmounted, ref } from "vue";
import paramsInfoSearch from "./paramsInfoSearch.vue";

interface ActualDataType {
  name?: string;
  data?: Array<any>;
  xAxisData?: Array<any>;
  [key: string]: any;
}

const routerQuery = inject("routerQuery", ref<Record<string, any>>({}));
const modelBoxTableRef = ref(null);
const title = ref<string>("实时参数");
const tableData = ref<Array<any>>([]);
const tableLoading = ref<boolean>(false);
const gap = 38;
const defaultHeight = 344;
const tableHeight = ref<number>(defaultHeight);
const previewSpecVisible = ref<boolean>(false);
const previewSpecData = ref<Record<string, any>>(null);
const eqpId = ref<string>("");
const quotaSingleCode = ref<string>("");
const actualData = ref<ActualDataType>({});
const loading = ref<boolean>(false);
const searchParams = ref<Record<string, any>>({ className: "", systemCode: "", quotaName: "" });
const defaultValueColor = "#fff";

const tableCloumns: Array<CommonTable.TableCloumnsType> = [
  {
    label: "科室",
    prop: "className",
    width: 60
  },
  {
    label: "系统",
    prop: "systemName",
    width: 110
  },
  {
    label: "子系统",
    prop: "twoSystemName",
    width: 120
  },
  {
    label: "点位",
    prop: "position",
    width: 90
  },
  {
    label: "指标名称",
    prop: "quotaName",
    width: 100,
    render({ row }: any) {
      const { quotaSingleCode: quotaSingleCode_ = "", quotaName = "", unit = "" } = row;
      quotaSingleCode.value = quotaSingleCode_;
      const previewFn = async () => {
        const res = await queryFabDetailParamsSpec({ quotaSingleCode: quotaSingleCode_ });
        if (!res) return;
        const { querySpcIndicatorDetailRespDTO = null, hourValueList = [] } = res;
        previewSpecData.value = querySpcIndicatorDetailRespDTO || null;
        actualData.value["name"] = `${quotaName}${unit ? "（" + unit + " ）" : ""}`;
        actualData.value["data"] = hourValueList.map(item => item.value);
        actualData.value["xAxisData"] = hourValueList.map(item => item.hourStr);
        previewSpecVisible.value = true;
      };
      return () => (
        <PxButton type="primary" text={true} class="params-info-quotaName-btn" onClick={previewFn}>
          {quotaName}
        </PxButton>
      );
    }
  },
  {
    label: "值",
    prop: "value",
    width: 80,
    render({ row }: any) {
      const { color = defaultValueColor, value = "" } = row;
      return () => (
        // 滤镜 + 对比度 + 反转
        <div style={{ color: color || defaultValueColor, backgroundColor: "currentColor" }}>
          <span style={{ filter: "grayscale(1) contrast(999) invert(1)", fontWeight: 600 }}>{value}</span>
        </div>
        // <div>
        //   <span style={{ color: "#fff", mixBlendMode: "difference" }}>{value}</span>
        // </div>
      );
    }
  },
  {
    label: "FSIM供应值",
    prop: "fsimSupplyValue",
    width: 100
  },
  {
    label: "单位",
    prop: "unit",
    width: 60
  },
  {
    label: "采集时间",
    prop: "acquisitionTime",
    width: 150
  }
];

const cellStyleFn = ({ row, column, rowIndex, columnIndex }) => {
  const { color = "" } = row;
  const backgroundColor = color || defaultValueColor;
  if (backgroundColor && columnIndex === 5) {
    return { backgroundColor };
  } else {
    return {};
  }
};

const searchChangeHandler = async (p: Record<string, any> = {}) => {
  const { className = null, systemCode = null, quotaName = null } = p;
  tableData.value.splice(0);
  loading.value = true;
  const { eqpId: eqpId_ = "" } = routerQuery.value;
  eqpId.value = eqpId_;
  const params = { eqpId: eqpId_, className, systemCode, quotaName };
  const res = await queryFabDetailParams(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res?.length) return;
  tableData.value = res;
};

const init = async () => {
  await searchChangeHandler();
  // tableData.value.splice(0);
  // loading.value = true;
  // const { eqpId: eqpId_ = "" } = routerQuery.value;
  // eqpId.value = eqpId_;
  // const res = await queryFabDetailParams({ eqpId: eqpId_ }, () => {
  //   loading.value = false;
  // });
  // loading.value = false;
  // if (!res?.length) return;
  // tableData.value = res;
};

const initSocketFn = () => {
  const { eqpId = "" } = routerQuery.value;
  // const eqpId = "YCCDA20";
  useFabDetailSocket(true, "FAB_DETAIL_PARAMETER", eqpId, jsonStr => {
    if (jsonStr) {
      const list = JSON.parse(jsonStr);
      if (!list?.length) return;
      tableData.value = list.reduce(
        (pre, cur) => {
          const index = pre.findIndex(item => item.quotaSingleCode === cur.quotaSingleCode);
          if (index > -1) {
            pre[index] = cur;
          } else {
            pre.unshift(cur);
          }
          return pre;
        },
        [...tableData.value]
      );
    }
  });
};

initSocketFn();

onMounted(async () => {
  await init();
  await useUpdateDomHeight(tableHeight, modelBoxTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <modelBox :title="title" slotTitleWidth="60%">
    <template #title>
      <paramsInfoSearch v-model="searchParams" @change="searchChangeHandler" />
    </template>
    <div v-show="!!tableData?.length" ref="modelBoxTableRef" v-loading="loading" class="params-info-content">
      <commonTable
        ref="commonTableRef"
        v-model="tableData"
        v-model:loading="tableLoading"
        mode="stripe"
        :border="false"
        :pagination="false"
        :height="tableHeight"
        :tableCloumns="tableCloumns"
        :cell-style="cellStyleFn"
      />
      <previewSpec
        v-if="previewSpecVisible"
        v-model="previewSpecVisible"
        :data="previewSpecData"
        :eqpId="eqpId"
        :quotaSingleCode="quotaSingleCode"
        :actualData="actualData"
      />
    </div>
    <div v-if="!tableData?.length" v-loading="tableLoading" class="params-info-content-empty">
      <px-empty class="px-empty-common" />
    </div>
  </modelBox>
</template>

<style lang="scss" scoped>
:deep(.params-info-quotaName-btn) {
  width: 100%;
  padding: 8px 0;

  & > span {
    display: block;
    width: 100%;
    overflow: hidden;
    text-align: left;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.params-info-content {
  width: 100%;
  height: 100%;
}

.params-info-content-empty {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
</style>
